package com.xymtop.api.interceptor;

import com.xymtop.api.config.Premission;
import com.xymtop.api.utils.MyCookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @ClassName : LoginInterCeptor
 * @Description : 拦截器，不该看的不给看
 * @Author : 肖叶茂
 * @Date: 2022/12/3  16:02
 */
@ControllerAdvice
public class LoginInterCeptor implements HandlerInterceptor {
    /**
     * Description : cookie，有则放行，没有则拦截
     *
     * @param request  请求对象
     * @param response 响应对象
     * @param handler  处理器（url+Controller：映射）
     * @return boolean
     * @date 2022/7/11
     **/
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        System.out.println(request.getCookies());
       String userid =  MyCookie.getCookie(request,"userid");
        if (userid != null||MyCookie.getCookie(request,"code").equals(Premission.LOGIN)) { //说明此时已登录
            return true;
        } else { //说明未登录
            //重定向至登录页面
//            response.sendRedirect("/");
            response.setHeader("Content-Type", "application/json;charset=UTF-8");//注意加上这一句
            String path = request.getContextPath();
            String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
            response.getWriter().write("{\n" +
                    "    \"status\": 500,\n" +
                    "    \"message\": \"没有登录\",\n" +
                    "    \"data\": null\n" +
                    "}");
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
